﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.Platform.Core;
using Baosight.ZNH.ZMCommon;
using Telerik.Windows.Controls;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.ZNH.ZMCP.UI.PopWindows;
using Telerik.Windows.Controls.GridView;
using Baosight.ZNH.ZMCP.UI.Blocks;
using Baosight.Platform.Core.UI;
using Microsoft.Practices.Unity;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;

namespace Baosight.ZNH.ZMCP.UI
{
    /// <summary>
    /// 采煤进度
    /// </summary>
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 张志芳
    /// Version: 1.0
    /// History:
    ///       2011-09-05  张志芳   [创建]
    ///
    public partial class ZMCPD1 : EFViewCmes
    {
        public ZMCPD1()
        {
            InitializeComponent();
            base.BeforeAction += OnBeforeAction;
        }

        public override void Initialize(EIInfo initData)
        {
            initData.AddBlock((new StatusBlock()).getStauts2());
            base.Initialize(initData);
        }

        /// <summary>
        /// 列表中修改、删除前设置属性、参数
        /// 传递到后台代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            base.ViewProperty = _view;
        }

        /// <summary>
        /// 点击新增按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            EIInfo eiInfo = new EIInfo();
            base.OnInsertButtonClickPopup(eiInfo, "采煤进度-新增", "insert", null, sender, e);
        }

        /// <summary>
        /// 点击修改按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();

            EIInfo eiInfo = new EIInfo();
            EIBlock eIBlock = new EIBlock("result");
            EIRow row = new EIRow();
            if (_list.Count > 0)
            {
                row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), _list[0]);
            }
            eIBlock.SetRow(0, row);
            eiInfo.AddBlock(eIBlock);

            base.OnUpdateButtonClickPopup(eiInfo, "采煤进度-修改", "update", null, sender, e);
        }

        /// <summary>
        /// 点击发布事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnReportButtonClick(object sender, RoutedEventArgs e)
        {
            base.OnModifyButtonClick("report", "发布", sender, e);
        }

        #region 退回按钮
        /// <summary>
        /// 点击退回事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnGobackButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;

            IList<EIRow> _list = this.grid.GetCheckedEIRows();
            if (_list.Count != 1)
            {
                base.OpenEFWindowAlert("选择一条记录进行退回操作", true);
                return;
            }

            BaseTools.OpenEFWindowConfirm("确定退回所选择的记录？", BackWindowConfirmClosed);
        }

        /// <summary>
        /// 确定退回所选记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BackWindowConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);//取消后，“改变状态”按钮生效
                return;
            }

            EIInfo info = new EIInfo();
            info.Set(EIConstants.ServiceNameKey, "ZMCPD1");
            info.Set(EIConstants.MethodNameKey, "hasReportData");
            EIBlock block = info.AddBlock(this.grid.eBlockName);
            block.SetColumns(this.grid.EIBlock.GetColumns());
            block.SetRows(this.grid.CheckedEIRows);
            base.Submit(info, HasReportDataCompleted);   //判断 是否数据来源于区队上报 
        }

        /// <summary>
        /// 是否数据来源于区队上报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HasReportDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)//数据来源于区队上报
            {
                if ("0".Equals(this.grid.GetCheckedEIRows()[0]["fdStatus"]))
                {
                    //直接将未发布的数据删除，并将区队的数据状态改为未上报
                    base.Submit(OperationMode.Update, this.eServiceName, "gobackTeam", DataRange.CheckedItems, DoModifyOperationCompleted);                
                }
                else
                {
                    //询问是否要退回到区队
                    DialogParameters param = new DialogParameters();
                    param.CancelButtonContent = "否";
                    param.OkButtonContent = "是";
                    param.Content = "是否要退回到区队上报模块中？";
                    param.Header = "确认框";
                    param.Closed = AskWindowsClosed;
                    EFWindow.Confirm(param);
                }
            }
            else
            {                
                if ("0".Equals(this.grid.GetCheckedEIRows()[0]["fdStatus"]))
                {
                    //状态为未发布的数据不能退回
                    base.OpenEFWindowAlert("该数据已经是最初状态，不能退回！", true);
                }
                else
                {
                    //状态为已发布的数据将数据状态改为未发布                    
                    base.Submit(OperationMode.Update, this.eServiceName, "goback", DataRange.CheckedItems, DoModifyOperationCompleted);
                }
            }
        }

        /// <summary>
        /// 是否将数据退回到区队
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AskWindowsClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null)
            {
                this.TempButtonOpen(true);//取消操作后，删除按钮生效
                return;
            }

            if (!e.DialogResult.Value)
            {
                //“否”——只将状态修改为未发布
                base.Submit(OperationMode.Update, this.eServiceName, "goback", DataRange.CheckedItems, DoModifyOperationCompleted);
            }
            else
            {
                //“是”——将数据删除，并将区队的数据状态改为未上报
                base.Submit(OperationMode.Update, this.eServiceName, "gobackTeam", DataRange.CheckedItems, DoModifyOperationCompleted);                
            }
        }
        #endregion

        /// <summary>
        /// 在删除和修改时进行校验，已上报的不能删除和修改
        /// </summary>
        /// <param name="_eIRows"></param>
        /// <returns></returns>
        public override bool BeforeMethod(List<EIRow> _eIRows)
        {
            foreach (EIRow row in _eIRows)
            {
                if (row["fdStatus"].Equals("1"))
                {
                    BaseTools.OpenEFWindowAlert("勾选的记录包含已发布记录，不能" + TempButton.Content + "，请重新选择!", null);
                    this.TempButtonOpen(true);
                    return false;
                }
            }
            
            return true;
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton link = sender as HyperlinkButton;
            EIRow row = (link.ParentOfType<GridViewRow>().Item as UIBaseEntity).GetEIRow();
            EIInfo eiInfo = new EIInfo();
            EIBlock eIBlock = new EIBlock("result");
            eIBlock.SetRow(0, row == null ? new EIRow() : row);
            eiInfo.AddBlock(eIBlock);

            base.OnHyperlinkButtonClickPopup(eiInfo, "采煤进度-查看", "detail", null, sender, e);
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InsertWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新Grid区域
                this.grid.Refresh();
                UpdateHomePageData(new EIInfo());
            }

            //按钮发布
            base.TempButtonOpen(true);

            //超链接发布
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }

        /// <summary>
        /// 新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public override void OpenPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cp.workNum"));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cp.department"));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cp.engineering"));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cp.group"));
            MineReportForLog view = new MineReportForLog(_dialogType);//构造一个新的修改页面
            view.EIDataContext = new Platform.Core.UI.EIDataContext();
            view.EIDataContext.Update(_eIInfo);

            if (_dialogType.Equals("insert"))
            {
                view.fdReporterId.Value = this.EIDataContext.GetAttribute("userId");
                ((view.fdReporterId.Content) as CmesCustomView).Display = this.EIDataContext.GetAttribute("userName");
                view.fdReporter.Value = this.EIDataContext.GetAttribute("userName");
                view.fdReportDepartmentId.Value = this.EIDataContext.GetAttribute("departmentId");
                view.fdReportDepartment.Value = this.EIDataContext.GetAttribute("departmentName");
                view.fdStatus.Value = "0";
            }
            else if (_dialogType.Equals("update"))
            {
                ((view.fdReporterId.Content) as CmesCustomView).Display = _eIInfo.GetBlock("result").GetRow(0)["fdReporter"];
            }
            else if (_dialogType.Equals("detail"))
            {
                ((view.fdReporterId.Content) as CmesCustomView).Display = _eIInfo.GetBlock("result").GetRow(0)["fdReporter"];
            }

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面  
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = view;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(InsertWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
        }

        /// <summary>
        /// 发布后通知主表更新数据
        /// </summary>
        /// <param name="data"></param>
        public override void UpdateHomePageData(EIInfo data)
        {
            IEventAggregator eventAggreator = Container.Resolve<IEventAggregator>();
            EIDataPublishedEvent dataPublishedEvent = eventAggreator.GetEvent<EIDataPublishedEvent>();
            dataPublishedEvent.Publish(data);
        }

    }
}
